package com.rizzo.analytics.services.web.delegator;


import com.rizzo.analytics.domain.account.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolderStrategy;

public abstract class RizzoDelegator {

    @Autowired
    @Qualifier("securityContextHolderStrategy")
    protected SecurityContextHolderStrategy securityContextHolderStrategy;

    protected String getUsernameFromContext() {
        return securityContextHolderStrategy.getContext().getAuthentication().getName();
    }

    protected boolean hasRoleAdmin() {
        final UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) securityContextHolderStrategy.getContext().getAuthentication();
        for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
            if (grantedAuthority.getAuthority().equals(Account.ROLE_ADMIN)) {
                return true;
            }
        }
        return false;
    }

}
